package role

import (
	"context"
	"database/sql"
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/sqlc"
	"go-admin/base/dao"

	"go-admin/base/internal/svc"
	"go-admin/base/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type SaveLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewSaveLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SaveLogic {
	return &SaveLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *SaveLogic) Save(req *types.RoleSaveReqDTO) (resp *types.RoleBooleanRespDTOS, err error) {

	if _, err = l.svcCtx.RoleModel.FindOneByName(l.ctx, req.RoleName); err != nil {
		if err != sqlc.ErrNotFound {
			_ = fmt.Errorf(err.Error())
			return nil, err
		}
	} else {
		return &types.RoleBooleanRespDTOS{
			Data: false,
			Result: types.Result{
				Code:    444,
				Message: "角色已存在！" + req.RoleName,
			},
		}, nil
	}

	if _, err = l.svcCtx.RoleModel.Insert(l.ctx, &dao.Role{
		Name: sql.NullString{
			String: req.RoleName,
			Valid:  true,
		},
	}); err != nil {
		_ = fmt.Errorf(err.Error())
		return nil, err
	}

	return &types.RoleBooleanRespDTOS{
		Data: true,
		Result: types.Result{
			Code: 200,
		},
	}, nil
}
